<template>
<div class="role-management-add views-container">
    <div class="wlm-form">
        <div class="wlm-form-header">代理权限</div>
        <div class="wlm-form-content">
            <el-form :ref="formFormatData.key" :model="formFormatData.formData" :rules="formFormatData.rules" size="small" label-width="120px" class="retail-form" label-position="right">
                <!-- <el-form-item label="角色名称">
                    <el-input v-model.trim="formFormatData.formData.name">
                    </el-input>
                </el-form-item>
                <el-form-item label="角色描述">
                    <el-input :autosize="{ minRows: 4, maxRows: 4}" type="textarea" v-model.trim="formFormatData.formData.role_describe">
                    </el-input>
                </el-form-item> -->
                <!-- <el-form-item label="状态">
                    <el-radio-group v-model="formFormatData.formData.is_use">
                        <el-radio :label="1">启用</el-radio>
                        <el-radio :label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item> -->
                <el-form-item label="操作权限">
                  <el-checkbox :indeterminate="isCheckAll" v-model="checkAllModel" @change="checkMainAll">全选</el-checkbox>
                    <div style="margin-top:20px;" v-for="(item, index) in formFormatData.formData.jurisdiction" :key="index">
                        <el-checkbox :indeterminate="item.isIndeterminates" v-model="item.checkAll" @change="handleCheckAllChange(item)" :disabled="item.path_disabled==1?true:false">{{item.title}}</el-checkbox>
                        <el-checkbox-group style="margin-left:50px;" v-model="item.checkList" @change="handlecheckedListChange(item)">
                            <el-checkbox v-for="(citem, cindex) in item.menu" :label="citem.path" :key="cindex" :disabled="citem.path_disabled==1?true:false">{{citem.title}}</el-checkbox>
                        </el-checkbox-group>
                    </div>
                </el-form-item>
                <!-- <el-form-item label="授权渠道">
                  <el-checkbox v-for="(item,index) in formFormatData.formData.power.totalChanel" :key="index" v-model="item.open">{{item.value}}</el-checkbox><br>
                </el-form-item> -->
                <el-form-item label="授权应用">
                  <el-checkbox v-for="(item,index) in formFormatData.formData.power.totalPlugins" :key="index" v-model="item.open" :disabled="item.path_disabled==1?true:false">{{item.value}}</el-checkbox>
                </el-form-item>
            </el-form>
        </div>
    </div>
    <div v-cloak class="wlm-fixed-btn flex-row flex-align-c flex-justify-c">
        <el-button size="small" @click="formFormatSubmit({ router: { type: 'replace', path: '/application/proxyauthority', code: 1 }})" type="primary">保存</el-button>
        <!-- <router-link tag="span" to="/permission/roleManagement">
            <el-button size="small">返回</el-button>
        </router-link> -->
    </div>
</div>
</template>

<script>
import {
  getStoreRoleInfo,
  updateStoreRoleInfo,
  getRoleMenu,
  addStoreRoleInfo
} from '@/api/setting'
import {
  storeMenu
} from '@/api/platform'
import mixins from '@/mixins/mixins'
export default {
  mixins: [mixins.getters('Form')],
  name: 'RoleManagementAdd',
  created() {
    this.$nextTick(()=>{
          getStoreRoleInfo({agent_user:1}).then(res=>{
          if(res.data.code==1){
              if(res.data.data.jurisdiction.length==0){
                   this.getstoreMenu()
                   this.getRoleMenubtn()
              }else{
                    if (Array.isArray(res.data.data.jurisdiction) && res.data.data.jurisdiction.length > 0) {
                        res.data.data.jurisdiction.map(item => {
                            const { menu, checkList } = item
                            item.checkAll = item.checkAll === 'true'
                            item.isIndeterminates = item.isIndeterminates === 'true'
                            item.menu = !Array.isArray(menu) ? [] : item.menu
                            item.checkList = !Array.isArray(checkList) ? [] : item.checkList
                        })
                        }
                        
                   this.formFormatData.formData.jurisdiction = res.data.data.jurisdiction
                   this.formFormatData.formData.power.totalPlugins = res.data.data.power.totalPlugins
              }
             
          }
            // console.log("飞机的说法跨境电商",res)
      })
    })
    // if (!this.$route.query.store_role_id) {
    //   getRoleMenu({agent_user:1}).then((response) => {
    //     const {
    //       data: {
    //         data: mesdata = []
    //       }
    //     } = response
    //     console.log("佛挡杀佛的科技属",mesdata)
    //     this.formFormatData.formData.jurisdiction = this.filters(mesdata)
    //     console.log(this.formFormatData.formData.jurisdiction)
    //   })
    // }
    // if (!this.isFormEdit) {
    //   this.getstoreMenu()
    // }
  },
  computed: {
    filterDeepItem() {
      return item => {
        return item.filter((citem) => {
          return Array.isArray(citem.menu)
        })
      }
    }
  },
  data() {
    return {
      isCheckAll: false,
      checkAllModel: false,
      formFormatData: {
        key: 'userForm',
        api: {
          editForm: {
            api: getStoreRoleInfo,
            params: {
                agent_user:1
            },
            redirect: 'agent_user'
          },
        //   submitForm: this.$route.query.store_role_id ? updateStoreRoleInfo : addStoreRoleInfo
          submitForm: addStoreRoleInfo
        },
        formData: {
        //   name: '',
          jurisdiction: [],
        //   is_use: 1,
        //   role_describe: '',
          power: {
            // totalChanel: {},
            totalPlugins: {}
          },
          agent_user:1
        },
        rules: {
          nickname: [{
            required: true,
            message: '请输入真实姓名',
            trigger: 'blur'
          }],
          username: [{
            required: true,
            message: '请输入用户手机号',
            trigger: 'blur'
          }
          ]
        }
      }
    }
  },
  methods: {
    checkMainAll(val) {
      console.log(val)
      if (val) {
        this.formFormatData.formData.jurisdiction.map(item => {
          const rusult = []
          item.checkAll = true
          //处理点击全选时，商家，商品，订单，数据的不确定状态
          if(item.title=='商家' || item.title=='商品' || item.title=='订单' || item.title=='数据'){
            item.isIndeterminates = true
          }
          item.menu.map(minItem => {
              if(minItem.path_disabled){
                  item.checkAll = false
              }
            rusult.push(minItem.path)
            
            item.checkList = rusult.filter(bitem=>{
                //处理全选，禁用的选项不让勾选
                return bitem!='merchantSettlement' && bitem!='merchantWithdraw'&& bitem!='merchantBalance' && bitem!='settlementSetting'
                         &&bitem!='managementUser' && bitem!='userLabel'&& bitem!='userBalance'
                          &&bitem!='goodsSetting'
                          &&bitem!='paySetting' &&bitem!='comeStore'
                          &&bitem!='basicdatas' && bitem!='kanbandata'&& bitem!='appletsdata'&& bitem!='distribution'
                          &&bitem!='basisSettings' && bitem!='otherSettings'&& bitem!='storageSettings'&& bitem!='paySettings'&& bitem!='payManagement'&& bitem!='pointBalance'
                          &&bitem!='livetelecast' && bitem!='livetelecastSet'&& bitem!='livegoods'&& bitem!='liveapplication'
                          &&bitem!='operationLog' && bitem!='cacheList'
            })
          })
        })
        // this.formFormatData.formData.power.totalChanel.map(item => {
        //   item.open = true
        // })
        // console.log(this.formFormatData.formData.power.totalPlugins, 'totalPlugins')
        // this.formFormatData.formData.power.totalPlugins.map(item => {
        //   item.open = true
        // })
        console.log(this.formFormatData.formData.jurisdiction, 'true')
      } else {
        this.formFormatData.formData.jurisdiction.map(item => {
          item.checkAll = false
          item.checkList = []
          //处理取消全选时，商家，商品，订单，数据的不确定状态
           if(item.title=='商家' || item.title=='商品' || item.title=='订单' || item.title=='数据'){
            item.isIndeterminates = false
          }
          // this.formFormatData.formData.power.totalChanel.map(item => {
          //   item.open = false
          // })
          // this.formFormatData.formData.power.totalPlugins.map(item => {
          //   item.open = false
          // })
        })
        console.log(this.formFormatData.formData.jurisdiction, 'false')
      }
    },
    filters(mesdata) {
      // 给每一个都加上isIndeterminates属性,默认为false
      mesdata.map(item => {
        item.checkAll = false
        item.checkList = []
        item.isIndeterminates = false
        if (item.menu) {
          item.menu.map(citem => {
            citem.checkAll = false
            citem.checkList = []
            citem.isIndeterminates = false
          })
        }
      })
      return mesdata
    },
   
    getstoreMenu() {
      storeMenu({agent_user:1}).then(res => {
        const { data: {  totalPlugins } } = res.data || {}
        this.formFormatData.formData.power.totalPlugins = totalPlugins
      })
    },
    getRoleMenubtn(){
         getRoleMenu({agent_user:1}).then((response) => {
        const {
          data: {
            data: mesdata = []
          }
        } = response
        this.formFormatData.formData.jurisdiction = this.filters(mesdata)
        console.log(this.formFormatData.formData.jurisdiction)
      })
    },
    
    formFormatCallBack(data, type, response) {
      if (type === 'editBeforeForm') {
        if (Array.isArray(data.jurisdiction) && data.jurisdiction.length > 0) {
          data.jurisdiction.map(item => {

            const { menu, checkList } = item
            item.checkAll = item.checkAll === 'true'
            item.isIndeterminates = item.isIndeterminates === 'true'
            item.menu = !Array.isArray(menu) ? [] : item.menu
            item.checkList = !Array.isArray(checkList) ? [] : item.checkList
          })
        }
      }
    },
    handleCheckAllChange(index) {
            console.log(index['checkList']['length'], 'index12123123121321')
            //处理点击单时，过滤禁用的选项
            const indexdata = index['menu'].filter(res=>{
              return res.path!='merchantSettlement' && res.path!='merchantWithdraw'&& res.path!='merchantBalance' && res.path!='settlementSetting'
                      &&res.path!='goodsSetting'
                      &&res.path!='paySetting' &&res.path!='comeStore'
                      &&res.path!='basicdatas' && res.path!='kanbandata'&& res.path!='appletsdata'&& res.path!='distribution'
                      &&res.path!='basisSettings' && res.path!='otherSettings'&& res.path!='storageSettings'&& res.path!='paySettings'&& res.path!='payManagement'&& res.path!='pointBalance'
                      &&res.path!='livetelecast' && res.path!='livetelecastSet'&& res.path!='livegoods'&& res.path!='liveapplication'
                      &&res.path!='operationLog' && res.path!='cacheList'
            })
      const menulen = indexdata['length']
      const currentlen = index['checkList']['length']
      if (menulen === currentlen) {
        index['checkList'] = []
      index['isIndeterminates'] = false

      } else {
        const arr = []
        index['menu'].map((item, index) => {
            console.log("发的好时机发多岁",item)
          arr.push(item.path)
        })
        index['checkList'] = arr.filter(bitem=>{
            //处理全选是，禁用的选项不让勾选
             return bitem!='merchantSettlement' && bitem!='merchantWithdraw'&& bitem!='merchantBalance' && bitem!='settlementSetting'
                         &&bitem!='managementUser' && bitem!='userLabel'&& bitem!='userBalance'
                          &&bitem!='goodsSetting'
                          &&bitem!='paySetting' &&bitem!='comeStore'
                          &&bitem!='basicdatas' && bitem!='kanbandata'&& bitem!='appletsdata'&& bitem!='distribution'
                          &&bitem!='basisSettings' && bitem!='otherSettings'&& bitem!='storageSettings'&& bitem!='paySettings'&& bitem!='payManagement'&& bitem!='pointBalance'
                          &&bitem!='livetelecast' && bitem!='livetelecastSet'&& bitem!='livegoods'&& bitem!='liveapplication'
                          &&bitem!='operationLog' && bitem!='cacheList'

        })
      }
    },
    handlecheckedListChange(index) {
      console.log('ssssssssssssss', index)
      const menulen = index['menu']['length']
      const currentlen = index['checkList']['length']
      index['checkAll'] = (menulen === currentlen)
      index['isIndeterminates'] = (currentlen > 0 && currentlen < menulen)
    }
  }
}
</script>
